using System.Text;
using System.Text.Json;

namespace ChatClient
{
    internal static class Program
    {
        #region field

        const string STR_SELF = "我：";

        const string STR_AI = "助手：";

        private static string mServerUrl;

        private static HttpClient mHttpClient;

        private static StringBuilder mTalkHistory = new();

        private static NewsClient mNewsClient;

        #endregion


        /// <summary>
        ///  The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            LoadConfig();
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            using (ProcessIcon pi = new ProcessIcon())
            {
                pi.Display();
                ShowChatWindow();
                Application.Run();
            }
        }

        public static void ShowChatWindow()
        {
            if (mNewsClient != null)
            {
                return;
            }

            mNewsClient = new NewsClient();
            mNewsClient.Show();
            mNewsClient.FormClosed += (sender, e) =>
            {
                mNewsClient = null;
            };

            mNewsClient.RefreshMessages();
        }

        public static void HideChatWindow()
        {
            mNewsClient?.Hide();
        }

        static void LoadConfig()
        {
            var curDir = Directory.GetCurrentDirectory();
            var filePath = Path.Join(curDir, "Config.json");
            if (!File.Exists(filePath))
            {
                MessageBox.Show("无法加载配置文件：Config.json");
                return;
            }

            var json = File.ReadAllText(filePath);
            var config = JsonSerializer.Deserialize<Config>(json);
            mServerUrl = config.server_url;
        }

        public static async Task SendMessage(string message, Action<string> callback)
        {
            message = message.Trim();
            if (string.IsNullOrEmpty(message))
            {
                return;
            }

            if (mHttpClient == null)
            {
                mHttpClient = new HttpClient();
            }

            mTalkHistory.AppendLine(STR_SELF);
            mTalkHistory.AppendLine(message);
            mTalkHistory.AppendLine();
            callback?.Invoke(message);

            var content = new StringContent($"{{\"question\":\"{message}\"}}", Encoding.UTF8, "application/json");
            try
            {
                // 发送 POST 请求并获取响应
                var response = await mHttpClient.PostAsync(mServerUrl, content);

                // 确保响应是成功的
                response.EnsureSuccessStatusCode();

                // 读取响应内容
                var responseBody = await response.Content.ReadAsStringAsync();
                mTalkHistory.AppendLine(STR_AI);
                var news = GetNewsFromResponse(responseBody);
                mTalkHistory.AppendLine(news);
                mTalkHistory.AppendLine();
                callback?.Invoke(news);
                Console.WriteLine(responseBody);
            }
            catch (HttpRequestException e)
            {
                // 处理请求异常
                Console.WriteLine($"请求错误: {e.Message}");
            }
        }

        private static string GetNewsFromResponse(string response)
        {
            var news = JsonSerializer.Deserialize<NewsResponse>(response);
            return news.message;
        }

        public static void ClearHistory()
        {
            mTalkHistory.Clear();
        }

        public static string GetTalkHistory()
        {
            return mTalkHistory.ToString();
        }
    }
}